<?php

/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/1
 * Time: 10:40
 */

namespace app\api\controller;



use app\api\model\AuditMaterialsEvaluate;
use redis\RedisPackage;
use app\api\model\Capital;
use app\api\model\OrderModel;
use app\api\model\Approval;
use think\Controller;
use think\Exception;
use app\api\model\Common;
use app\index\model\Jpush;
use think\Request;



class Polling extends Controller
{
    /*
     * 师傅材料审核
     */
    public function masterMaterialReview(RedisPackage $redis)
    {

        $material_usage = db('material_usage', config('database.zong'))->where(['status' => 0, 'types' => 2])->where('created_time', '>', 1730995200)->where("FROM_UNIXTIME(created_time, '%Y-%m-%d')+  INTERVAL 2 DAY <= CURDATE() ")->select();
        foreach ($material_usage as $item) {
            $ID = $item['id'];
            $antiDuplication = 'cailiaozidong';
            $expire = 3600;
            // 设置缓存 设置缓存过期时间
            $tt = $redis->get(md5($ID . $antiDuplication));
            if ($tt) {
                continue;
            }
            $redis->set(md5($ID . $antiDuplication), md5($ID . $antiDuplication), $expire);
            db()->startTrans();
            try {
                $db = Common::city($item['order_id']);
                $orderList = db('order', config('database.' . $db['db']))->join('store', 'order.store_id=store.store_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->field('store.Inventory,order.cleared_time,order.store_id,user.registrationId,order.assignor')->where('order_id', $item['order_id'])->find();

                if (!empty($orderList['cleared_time'])) {
                    throw new Exception('该订单已结算');
                }
                if ($orderList['Inventory'] == 1) {
                    throw new Exception('库存盘点');
                }
                $code       = $item['code'];
                $unit_price = 0;
                if ($item['status'] != 1) {
                    $op  = u8queryForStoreId($code, $orderList['store_id']);
                    $u8c = json_decode($op, true);
                    if ($u8c['status'] == 'success') {
                        $number = $u8c['data'];
                        if (!is_array($number)) {
                            $number = json_decode($u8c['data'], true);
                        }
                        if ($number['datas'][0]['nnum'] - $item['square_quantity'] < 0) {
                            throw new Exception('库存不足');
                        } else {
                            $Leftover = $number['datas'][0]['nnum'] - $item['square_quantity'];
                            if ($Leftover >= 0) {
                                $inter    = u8insertU8c($orderList['store_id'], $item['order_id'], $item['square_quantity'], $code, 0, $item['id']);
                                $U8cinter = json_decode($inter, true);
                                if ($U8cinter['status'] != 'success') {
                                    throw new Exception($U8cinter['errormsg']);
                                }
                                $materialCostSellingPrice = $U8cinter['data']['materialCostSellingPrice']; //材料成本售价
                                $materialCostUnitPrice = $U8cinter['data']['materialCostUnitPrice']; // 材料成本单价
                                $status     = 1;
                                $total_price      =  round(($item['square_quantity'] * $materialCostSellingPrice), 2);
                                $total_profit      =  round(($item['square_quantity'] * $materialCostUnitPrice), 2);
                                $app_user   = db('app_user', config('database.' . $db['db']))->where('id', $item['user_id'])->find();
                                //材料领用
                                db('material_usage', config('database.' . $db['db']))->where(['id' => $item['id']])->update(['status' => $status, 'content' => $app_user['username'] . '师傅提交的材料领用，已过24小时，因您未审核，系统已自动审核通过', 'unit_price' => $materialCostSellingPrice, 'total_price' => $total_price, 'total_profit' => $total_profit, 'adopt' => time()]);

                                if (!empty($orderList['registrationId'])) {
                                    $push = new Jpush();
                                    $data = array('order_id' => $item['order_id'], 'content' => $app_user['username'] . '师傅提交的材料领用，已过24小时，因您未审核，系统已自动审核通过', 'type' => 9, 'user_id' => $orderList['assignor']);
                                    $push->tui('', $orderList['registrationId'], $data, $db['db']);
                                }
                            } else {
                                throw new Exception('库存不足');
                            }
                        }
                    } else {
                        throw new Exception('请求异常，请稍后再试');
                    }
                }
                db()->commit();
            } catch (Exception $e) {
                db()->rollback();
                db('log', config('database.zong'))->insert(['admin_id' => 99, 'created_at' => time(), 'content' => json_encode($item), 'type' => 199, 'msg' => $e->getMessage()]);
            }
        }
    }

    /*
   * 代购主材推送提醒
   */
    public function PurchasingAgentMainMaterialPushReminder()
    {
        $material_usage = db('agency_order', config('database.zong'))->join('order', 'order.order_id=agency_order.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->join('user user_deliverer', 'user_deliverer.user_id=order.deliverer', 'left')->where(['agency_order.status' => 13])->where('agency_order.delete_time', 0)->where('agency_order.last_payment_add_time', 0)->where('completion_time', '>', 1730995200)->where("FROM_UNIXTIME(completion_time, '%Y-%m-%d')+  INTERVAL 3 DAY <= CURDATE() ")->field('agency_order.*,if(order.deliverer=0,order.assignor,order.deliverer) as assignor,if(order.deliverer=0,user.registrationId,user_deliverer.registrationId) as registrationId')->select();
        foreach ($material_usage as $item) {
            if (!empty($item['registrationId'])) {
                $push = new Jpush();
                $db = Common::city($item['order_id']);
                $data = array('order_id' => $item['order_id'], 'content' => '有主材已待验收，请及时验收，4天后将自动验收通过', 'type' => 51, 'user_id' => $item['assignor']);
                $push->tui('', $item['registrationId'], $data, $db['db']);
            }
        }
    }

    /*
   * 代购主材自动验收
   */
    public function AutomaticAcceptanceOfPurchasingMainMaterials(Capital $capital, OrderModel $orderModel, AuditMaterialsEvaluate $auditMaterialsEvaluate, Common $common, RedisPackage $redis)
    {
        $material_usage = db('agency_order', config('database.zong'))->join('order', 'order.order_id=agency_order.order_id', 'left')->join('user', 'user.user_id=order.assignor', 'left')->join('user user_deliverer', 'user_deliverer.user_id=order.deliverer', 'left')->where(['agency_order.status' => 13])->where("FROM_UNIXTIME(completion_time, '%Y-%m-%d')+  INTERVAL 7 DAY <= CURDATE() ")->where('completion_time', '>', 1730995200)->where('agency_order.delete_time', 0)->where('agency_order.last_payment_add_time', 0)->field('agency_order.*,if(order.deliverer=0,order.assignor,order.deliverer) as assignor,if(order.deliverer=0,user.registrationId,user_deliverer.registrationId) as registrationId,if(order.deliverer=0,user.username,user_deliverer.username) as username,if(order.deliverer=0,user.store_id,user_deliverer.store_id) as store_id')->select();
        foreach ($material_usage as $item) {
            $ID = $item['order_id'];
            $antiDuplication = 'yanshouzidong';
            $expire = 3600;
            // 设置缓存 设置缓存过期时间
            $tt = $redis->get(md5($ID . $antiDuplication));
            if ($tt) {
                continue;
            }

            $redis->set(md5($ID . $antiDuplication), md5($ID . $antiDuplication), $expire);
            $created_time = time();
            $db = Common::city($item['order_id']);
            $agency_incre = \db('agency_incre', config('database.' . $db['db']))->where('agency_order_id', $item['id'])->select();
            if (!empty($agency_incre)) {
                echo json_encode($agency_incre);
                continue;
            }
            $auditMaterialsEvaluate->connect(config('database.' . $db['db']));
            $orderModel->connect(config('database.' . $db['db']));
            $capital->connect(config('database.' . $db['db']));
            $agency_task = \db('agency_task', config('database.' . $db['db']))->where('agency_task.status', '<>', 2)->where('agency_order_id', $item['id'])->where('delete_time', 0)->select();
            $capitalId = array_column($agency_task, 'capital_id');
            $capital->startTrans();
            db()->startTrans();
            try {
                $prove       = json_decode('["https://images.yiniao.co/20241108001251.png"]', true);
                $Select      = json_decode('[{"choice":[{"id":1,"select":1,"title":"很好"}],"title":"质量评价","type":1},{"choice":[{"id":1,"select":1,"title":"很好"}],"title":"时效评价","type":2},{"choice":[{"id":1,"select":1,"title":"很好"}],"title":"供应商服务评价","type":3},{"choice":[{"id":1,"select":1,"title":"很好"}],"title":"客户满意度评价","type":4},{"choice":[{"id":1,"select":1,"title":"很好"}],"title":"内部满意度评价","type":5}]', true);
                $evaluate    = [];
                $capitalFind = $capital->QueryOne($capitalId[0]);
                if (!empty($capitalFind['acceptance'])) {
                    throw new Exception('当前主材尾款放款审批中，请勿重复操作');
                }
                $evaluateLisy = [];
                foreach ($capitalId as $key => $o) {
                    $id = db('audit_materials', config('database.' . $db['db']))->insertGetId(['prove' => empty($prove) ? '' : serialize($prove), 'materials_remarks' => '', 'capital_id' => $o, 'user_id' => $item['assignor'], 'creationtime' => $created_time, 'store_id' => $item['store_id']]);
                    foreach ($Select as $k => $value) {
                        foreach ($value['choice'] as $list) {
                            $evaluate[] = ['type' => $value['type'], 'evaluate' => $list['id'], 'materials_id' => $id,];
                        }
                    }
                    $evaluateLisy[] = $evaluate;
                    $capital->isUpdate(true)->save(['acceptance' => $id, 'capital_id' => $o]);
                }
                $reimbursementId = null;
                if (!empty($evaluateLisy)) {
                    $auditMaterialsEvaluate->saveAll($evaluate);
                }
                $result = array();
                foreach ($agency_task as $k => $v) {
                    $result[$v['agency_id']][] = $v;
                }
                $agency_order_sub           = \db('agency_order_sub', config('database.' . $db['db']))->where('agency_order_id', $item['id'])->select();
                $agency_order_subAttachment = [];
                foreach ($agency_order_sub as $i) {
                    $m = json_decode($i['attachment'], true);
                    if ($m) {
                        foreach ($m as $j) {
                            array_push($agency_order_subAttachment, $j['url']);
                        }
                    }
                }

                $attachmentZong         = json_decode($item['attachment'], true);
                $attachmentZong = empty($attachmentZong) ? [] : array_column($attachmentZong, 'url');
                $attachment             = serialize(array_merge($attachmentZong, $agency_order_subAttachment));
                $total_cost             = array_sum(array_column($agency_task, 'total_cost'));
                $first_reimbursement_id = array_column($agency_order_sub, 'first_reimbursement_id');
                $reimbursement          = \db('reimbursement', config('database.' . $db['db']))->whereIn('id', $first_reimbursement_id)->where('status', 1)->sum('money');
                $money                  = 0;
                $op                     = ['order_id' => $item['order_id'], 'reimbursement_name' => $capitalFind['class_b'] . "等主材尾款请款", 'money' => round($total_cost - $reimbursement, 2), 'voucher' => $attachment, 'created_time' => $created_time, 'user_id' => $item['assignor'], 'status' => 3, 'sp_no' => '', 'content' => '此单为店长超时不验收主材，触发系统自动验收，请与店长确认金额是否正常', 'classification' => 4, 'submission_time' => $created_time, 'shopowner_id' => $item['assignor'], 'capital_id' => implode(",", array_column($agency_task, 'capital_id')), 'payment_notes' => '', 'secondary_classification' => 17];
                $reimbursementId      = db('reimbursement', config('database.' . $db['db']))->insertGetId($op);
                $reimbursement_agency = [];
                if ($reimbursementId) {
                    foreach ($result as $k => $value) {
                        $reimbursementRelationMoney = db('reimbursement_relation', config('database.' . $db['db']))->whereIn('reimbursement_id', $first_reimbursement_id)->where('bank_id', $k)->value('money');
                        db('reimbursement_relation', config('database.' . $db['db']))->insertGetId(['reimbursement_id' => $reimbursementId, 'capital_id' => implode(",", array_column($result[$k], 'capital_id')), 'bank_id' => $k, 'money' => array_sum(array_column($result[$k], 'total_cost')) - $reimbursementRelationMoney, 'receipt_number' => "NO" . $created_time]);
                    }
                }
                \db('agency_order', config('database.' . $db['db']))->where('id', $item['id'])->update(['last_payment_add_time' => $created_time]);
                \db('agency_order_sub', config('database.' . $db['db']))->where('agency_order_id', $item['id'])->update(['last_reimbursement_id' => $reimbursementId]);
                \db('reimbursement', config('database.' . $db['db']))->where('id', $reimbursementId)->setInc('money', $money);
                $approval        = new Approval();
                $title           = array_search(4, array_column($approval->listReimbursement(), 'type'));
                $title           = $item['username'] . $approval->listReimbursement()[$title]['name'] . '报销';
                db()->commit();
                $capital->commit();
                $auditMaterialsEvaluate->commit();
                if ($reimbursementId) {
                    $approval->Reimbursement($reimbursementId, $title, $item['username'], 4, 5, '', 1);
                }
                $totalCapital   = $capital->where(['ordesr_id' => $item['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
                $alreadyCapital = $capital->where('acceptance', '<>', 0)->where(['ordesr_id' => $item['order_id'], 'types' => 1, 'enable' => 1, 'agency' => 1])->count();
                if ($totalCapital == $alreadyCapital) {
                    $orderModel->isUpdate(true)->save(['order_id' => $item['order_id'], 'acceptance_time' => $created_time]);
                }
                if (!empty($item['registrationId'])) {
                    $push = new Jpush();
                    $data = array('order_id' => $item['order_id'], 'content' => $capitalFind['class_b'] . '..已自动验收通过，按照系统金额生成了付款审批，若有问题，请联系商圈总驳回', 'type' => 51, 'user_id' => $item['assignor']);
                    $push->tui('', $item['registrationId'], $data, $db['db']);
                }
            } catch (Exception $e) {
                $capital->rollback();
                db()->rollback();
                $auditMaterialsEvaluate->rollback();
                db('log', config('database.zong'))->insert(['admin_id' => 99, 'created_at' => $created_time, 'content' => json_encode($item), 'type' => 200, 'msg' => $e->getMessage()]);
            }
        }
    }

    public function award_config_rule()
    {
        $get = Request::instance()->get();
        $Common     = new Common();
        $orderModel = new OrderModel();
        $Common->award_config_rule($get['order_id'], $orderModel, 3);
    }

    /**
     * 
     * @return void
     */

    public function ImageProcessing()
    {
        $order_resource = \db('order_resource')->where('mime_type', 1)->select();
        foreach ($order_resource as $value) {
            $img = 'https://images.yiniao.co' . $value['path'];
            $headers =  get_headers($img, 1);
            if ($headers && strpos($headers[0], '200 OK') === false) {

                continue; // 跳过当前资源
            }
            $path      = parse_url($img)['path'];
            if ($headers['Content-Type'] == "video/mp4") {
                $getRemoteVideoInfo = $this->getRemoteVideoInfo($img);
                $mime_type = $getRemoteVideoInfo['mime_type'];
                $size     = $getRemoteVideoInfo['size_bytes'];;
            } else {
                $mime_type =  getimagesize($img)['mime'];

                if (isset($headers['Content-Length'])) {
                    $fileSize = $headers['Content-Length'];
                    $size     = $fileSize;
                } else {
                    $size = 0;
                }
            }

            db('order_resource')->where('id', $value['id'])->update(['mime_type' => empty($mime_type) ? 'image/jpeg' : $mime_type, 'path' => $path, 'size' => $size ?? 0]);
        }

        $common_resource =  \db('common_resource')->where('mime_type', 1)->select();
        foreach ($common_resource as $value) {
            $img = 'https://images.yiniao.co/' . $value['path']; 
            $headers =  get_headers($img, 1);
            if ($headers && strpos($headers[0], '200 OK') === false) {

                continue; // 跳过当前资源
            }
            $path      = parse_url($img)['path'];
            if ($headers['Content-Type'] == "video/mp4") {
                $getRemoteVideoInfo = $this->getRemoteVideoInfo($img);
                $mime_type = $getRemoteVideoInfo['mime_type'];
                $size     = $getRemoteVideoInfo['size_bytes'];;
            } else {
                $mime_type =  getimagesize($img)['mime'];

                if (isset($headers['Content-Length'])) {
                    $fileSize = $headers['Content-Length'];
                    $size     = $fileSize;
                } else {
                    $size = 0;
                }
            }
            db('common_resource')->where('id', $value['id'])->update(['mime_type' => empty($mime_type) ? 'image/jpeg' : $mime_type, 'path' => $path, 'size' => $size ?? 0]);
        }
        jso_data(0, 200, "成功");
    }
    function getRemoteVideoInfo(string $remoteVideoUrl)
    {
        // 1. 初始化 CURL
        $ch = curl_init($remoteVideoUrl);
        if (!$ch) {
            echo "错误：CURL 初始化失败";
            return false;
        }

        // 2. 设置 CURL 关键选项（仅获取头信息，不下载内容）
        curl_setopt_array($ch, [
            CURLOPT_NOBODY => true,                  // 不获取响应体（视频内容）
            CURLOPT_RETURNTRANSFER => true,          // 结果转为字符串，不直接输出
            CURLOPT_HEADER => true,                  // 包含响应头信息
            CURLOPT_FOLLOWLOCATION => true,          // 自动跟随 301/302 重定向（避免链接跳转导致的错误）
            CURLOPT_TIMEOUT => 15,                   // 超时时间（秒），防止卡住
            CURLOPT_SSL_VERIFYPEER => false,         // 关闭 SSL 证书验证（若 URL 是 HTTPS，且证书无效时启用）
            CURLOPT_SSL_VERIFYHOST => false,         // 关闭 SSL 主机验证（同上，生产环境建议开启并配置证书）
            // 模拟浏览器请求（应对部分服务器的防盗链限制）
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
        ]);

        // 3. 执行 CURL 请求
        $response = curl_exec($ch);
        if ($response === false) {

            curl_close($ch);
            return [
                'mime_type' => 0,
                'size_bytes' => 0,
                'size_mb' => 0
            ];
        }

        // 4. 解析响应结果
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 获取 HTTP 状态码
        $mime_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); // 获取 MIME 类型
        $size_bytes = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD); // 获取文件体积（字节）

        // 关闭 CURL
        curl_close($ch);

        // 5. 验证请求是否成功（HTTP 200 = 正常）
        if ($httpCode !== 200) {
            return [
                'mime_type' => 0,
                'size_bytes' => 0,
                'size_mb' => 0
            ];
        }

        // 6. 处理文件体积（单位换算为 MB，保留 2 位小数）
        $size_mb = $size_bytes ? round($size_bytes / 1024 / 1024, 2) : '未知';

        // 返回结果
        return [
            'mime_type' => $mime_type,
            'size_bytes' => $size_bytes,
            'size_mb' => $size_mb
        ];
    }
    public function gou_list() {
        die;
     $ca   = db('envelopes')
       ->join('order_times', 'order_times.order_id=envelopes.ordesr_id', 'left')
        ->field('envelopes.*,order_times.signing_time')
        ->where('envelopes.delete_time', 0)
        ->where('envelopes.total_price',0)
        ->select();
        echo db('envelopes')->getLastSql();die;
        $da   = [];
        foreach ($ca as $k => $item) {
            if ($item['type'] == 1) {
                $cap = db('capital')->where(['envelopes_id' => $item['envelopes_id'], 'types' => 1, 'enable' => 1])->field('to_price,crtime,envelopes_id,fen,give,agency,products_v2_spec,products,is_product_choose')->select();
            } else {
                $cap = db('capital')->where(['envelopes_id' => $item['envelopes_id'], 'types' => 1])->field('to_price,crtime,envelopes_id,fen,give,agency,products_v2_spec,products,is_product_choose')->select();
            }
            $to_price    = 0;
            $agencyMoney    = 0;
            $MainMoney    = 0;
            foreach ($cap as $l) {
                if ($l['products'] == 1 && $l['products_v2_spec'] != 0 && $l['is_product_choose'] == 1) {
                    $to_price += $l['to_price'];
                }
                if ($l['products'] == 0) {
                    $to_price += $l['to_price'];
                }
                if ($l['products'] == 1 && $l['products_v2_spec'] == 0) {
                    $to_price += $l['to_price'];
                }
                if ($l['agency'] == 1) {
                    $agencyMoney += $l['to_price'];
                }
                if ($l['agency'] == 0) {
                    $MainMoney += $l['to_price'];
                }
            }
            
            if ($item['signing_time'] == 0) {
                $item['give_money']          = (string)round($item['give_money'] - $item['main_round_discount'], 2);
                $item['purchasing_discount'] = (string)round($item['purchasing_discount'] - $item['purchasing_round_discount'], 2);
                
            }
            $da[$k]['give_money']          = (string)round($item['give_money'], 2);
            $da[$k]['purchasing_expense']  = (string)round($item['purchasing_expense'], 2);
            $da[$k]['purchasing_discount'] = $item['purchasing_discount'];
            $da[$k]['amount']              = sprintf('%.3f', ($agencyMoney+$MainMoney) + ($item['expense'] + $item['purchasing_expense']) - ($da[$k]['give_money'] + $da[$k]['purchasing_discount']));
            \db('envelopes')->where('envelopes_id',$item['envelopes_id'])->update(['main_price'=>$MainMoney+$item['expense']-$da[$k]['give_money'],'agent_price'=>$agencyMoney+$item['purchasing_expense']-$da[$k]['purchasing_discount'],'total_price'=>$da[$k]['amount']]);
            
        }
        r_date($da, 200);
    }
}
